//
//  ThirdpartyPhoneViewController.m
//  Molian
//
//  Created by 小蚕 on 15/9/8.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "ThirdpartyPhoneViewController.h"
#import "MLLoginTextField.h"

@interface ThirdpartyPhoneViewController ()

@property (strong,nonatomic)MLLoginTextField *CAPTCHAnumber;
@property (strong,nonatomic)BFPaperButton *again;
///号码接口
@property (strong,nonatomic)MLLoginTextField *phonenumber;

@property NSInteger countdownTime;
@property (strong, nonatomic) NSTimer *updateCodeTimer;
@end

@implementation ThirdpartyPhoneViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     self.navigationController.navigationBar.hidden = NO;

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"绑定手机号";
    NSString *str;
    if (self.noRegister) {
        str = @"完成";
    }else{
        str = @"下一步";
    }
    
    UIBarButtonItem *rightItem  = [[UIBarButtonItem alloc]initWithTitle:str style:UIBarButtonItemStylePlain target:self action:@selector(rightItem)];
    self.navigationItem.rightBarButtonItem = rightItem;
    UIButton *leftBt = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBt sizeToFit];
    [leftBt setTitle:@"返回" forState:UIControlStateNormal];
    [leftBt setContentMode:UIViewContentModeCenter];
    [leftBt setImage:[UIImage imageNamed:@"back_normal"] forState:UIControlStateNormal];
    [leftBt setImageEdgeInsets:UIEdgeInsetsMake(-2,-18, -2, 0)];
    [leftBt setTitleEdgeInsets:UIEdgeInsetsMake(0, -12, 0, -10)];
    leftBt.titleLabel.font = kFont(17);
    leftBt.frame = CGRectMake(0, 0, 40, 30);
    leftBt.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [leftBt addTarget:self action:@selector(clickLeftBt) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarBt = [[UIBarButtonItem alloc] initWithCustomView:leftBt];
    self.navigationItem.leftBarButtonItems = @[leftBarBt];
    //手机号码文本框
    self.phonenumber = [[MLLoginTextField alloc]initWithFrame:CGRectMake(0, 80, DeviceWidth, 40)];
    self.phonenumber.placeholder = @"请输入手机号码";
    self.phonenumber.keyboardType = UIKeyboardTypePhonePad;
    self.phonenumber.leftPrompt = @"  手机号  ";
    [self.view addSubview:self.phonenumber];
    [self.phonenumber style];

    
    //第一次输入密码
    self.CAPTCHAnumber = [[MLLoginTextField alloc]initWithFrame:CGRectMake(0, 120, DeviceWidth, 40)];
    self.CAPTCHAnumber.placeholder = @"请输入验证码";
    self.CAPTCHAnumber.leftPrompt = @"  验证码  ";
    self.CAPTCHAnumber.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:self.CAPTCHAnumber];
    self.CAPTCHAnumber.toBeNumber = 6;
    [self.CAPTCHAnumber style];
    
    //获取验证码按钮
    self.again = [[BFPaperButton alloc]initWithFrame:CGRectMake(DeviceWidth-110, 125, 100, 30)raised:NO];
    [self.again setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.again setTitleColor:APPCOLOR(1) forState:UIControlStateNormal];
    self.again.layer.masksToBounds = YES;//开启圆角
    [self.again.layer setCornerRadius:15];
    [self.again addTarget:self action:@selector(getVirifyCode:) forControlEvents:UIControlEventTouchUpInside];
    [self.again.layer setBorderColor:APPCOLOR(1) .CGColor];
    [self.again.layer setBorderWidth:1];
    self.again.titleLabel.adjustsFontSizeToFitWidth = YES;
    self.again.titleLabel.font = [UIFont fontWithName:FontName size:14];
    [self.view addSubview:self.again];
    
    
    //密码提示
    UILabel *prompt = [[UILabel alloc]initWithFrame:CGRectMake(0, 170, DeviceWidth, 20)];
    prompt.text = @"验证码有效期为10分钟";
    prompt.textColor = [UIColor grayColor];
    prompt.textAlignment = NSTextAlignmentCenter;
    prompt.font = [UIFont fontWithName:FontName size:13];
    [self.view addSubview:prompt];
    
    //
    UILabel *prompt1 = [[UILabel alloc]initWithFrame:CGRectMake(15, 170+30, DeviceWidth-30, 60)];
    prompt1.numberOfLines = 0;
    prompt1.text = @"为避免骚扰，从此版本起，用户需要绑定手机号才能正常使用，给您造成不便敬请谅解。\n(手机号只用于验证账号，不作为登录账号使用)";
    prompt1.textColor = [UIColor grayColor];
    //prompt1.textAlignment = NSTextAlignmentCenter;
    prompt1.font = [UIFont fontWithName:FontName size:13];
    [self.view addSubview:prompt1];
    

    // Do any additional setup after loading the view.
}
- (void)clickLeftBt
{
    [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:YES completion:^(NSDictionary *info, EMError *error) {
        [HUD hideFromViewAnimated:YES];
        if (error == nil) {
            
         
            [self.navigationController popToRootViewControllerAnimated:YES];
            
            //退出登录的全局操作
            [Utils quitLogin];
            
            [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"MLOUT"];
            self.hidesBottomBarWhenPushed = NO;
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        }else{
            
            [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:YES completion:^(NSDictionary *info, EMError *error) {
                [HUD hideFromViewAnimated:YES];
                if (error == nil) {
                    
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    
                    //退出登录的全局操作
                    [Utils quitLogin];
                    
                    [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"MLOUT"];
                    self.hidesBottomBarWhenPushed = NO;
                    [self.navigationController popToRootViewControllerAnimated:YES];
                   
                }else{
                    [HUD Prompt:@"退出失败"];
                    
                }
                
            } onQueue:nil];
            
        }
        
    } onQueue:nil];
}


//确
-(void)rightItem
{
     NSString *phone = self.phonenumber.text;
    if ([phone isEqualToString:@""]) {
        [HUD Prompt:@"请输入手机号"];
        return;
    }
    
    NSString *verifyCode = self.CAPTCHAnumber.text;

    if ([verifyCode isEqualToString:@""]) {
        [HUD Prompt:@"请输入收到的验证码"];
        return;
    }
   
    __weak ThirdpartyPhoneViewController *weakSelf = self;
    
    [AVOSCloud verifySmsCode:verifyCode mobilePhoneNumber:self.phonenumber.text callback:^(BOOL succeeded, NSError *error) {
        // 处理校验验证码后的返回值
        if (succeeded) {
            MPUser *user = [MPUser currentUser];
            user.notifyPhoneNum = phone;
            [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (error) {
                    [HUD Prompt:@"绑定失败,返回重试"];
                }else{
                    [HUD Prompt:@"绑定成功"];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                    
                }
            }];
        }
        else {
            NSString *msg = @"验证失败,请检查验证码是否正确";
            if (error.code == AVOS_RES_CODE_SMS_CODE_INVALID) {
                msg = @"验证码错误";
            }
            [HUD Prompt:msg ];
        }
    }];
    
}


// 获取验证码
- (void)getVirifyCode:(BFPaperButton *)sender {
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    //[dict setObject:@"MyName" forKey:@"username"];
    [dict setObject:@"MyApplication" forKey:@"口袋恋人"];
    if (self.phonenumber&&self.phonenumber.text.length>0) {
        AVQuery *query1 = [MPUser query];
        [query1 whereKey:@"notifyPhoneNum" equalTo:self.phonenumber.text];
        AVQuery *query2 = [MPUser query];
        [query2 whereKey:@"mobilePhoneNumber" equalTo:self.phonenumber.text];
        AVQuery *query = [AVQuery orQueryWithSubqueries:[NSArray arrayWithObjects:query1,query2, nil]];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (error) {
                [HUD Prompt:@"网络错误"];
            }else{
                if (objects&&objects.count>0) {
                    [HUD Prompt:@"该手机号已经绑定过了"];
                }else{
                    [AVOSCloud requestSmsCodeWithPhoneNumber:self.phonenumber.text templateName:nil variables:dict callback:^(BOOL succeeded, NSError *error) {
                        // 执行结果
                        if (succeeded) {
                            [HUD hideFromViewAnimated:YES];
                            [self.CAPTCHAnumber becomeFirstResponder];
                            // 获取验证码成功,禁用按钮
                            [self.again setEnabled:NO];
                            self.countdownTime = 60;
                            [self.again setTitle:@"重新获取" forState:UIControlStateNormal];
                            // 启动定时器
                            self.updateCodeTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateCountdownTime) userInfo:nil repeats:YES];
                        } else {
                            NSString *msg = @"获取失败,请重试";
                            if (AVOS_RES_CODE_PHONE_NOT_EXIST == error.code) {
                                msg = @"手机号码不存在";
                            }
                            [HUD Prompt:msg ];
                        }
                    }];
                }
            }
        }];
    }else{
        [HUD Prompt:@"请输入手机号码"];
    }
}

// 修改获取验证码的倒计时
- (void)updateCountdownTime {
    self.countdownTime -=  1;
    NSString *time = [NSString stringWithFormat:@"%lds", (long)self.countdownTime];
    [self.again setTitle:time forState:UIControlStateNormal];
    // 处理倒计时结束
    if (self.countdownTime == 0) {
        [self.again setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.again setEnabled:YES];
        [self.again setBackgroundColor:[UIColor whiteColor]];
        [self.updateCodeTimer invalidate];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
